package com.zx.scp.controller;

import java.text.MessageFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.bcloud.msg.http.HttpSender;
import com.zx.map.service.MessageSendLogService;
import com.zx.map.service.model.MessageSendLogModel;
import com.zx.mobile.MobileCommonHelper;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.scp.service.model.MessageRequestModel;
import com.zx.scp.service.model.MessageResponse;
import com.zx.scp.utils.PropertyUtil;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-6-7 Time: 上午1:08 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/message")
public class MessageSendController {  
	
	
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(MessageSendController.class);
	private static final String MESSAGESETTLETYPE = "尊敬的用户，您的手机验证码为${code}，本验证码仅用于修改结算周期，1分钟之内有效，请及时查收！";
	private static final String MESSAGEFORGETPWD = "尊敬的用户，您的手机验证码为${code}，本验证码仅用于重新设置密码验证，1分钟之内有效，请及时查收！";
	private static final String MESSAGEREGISTER = "尊敬的用户，您的手机验证码为${code}，本验证码仅用于注册验证，1分钟之内有效，请及时查收！";
	private static final String MESSAGEREVIEW = "尊敬的用户，您提交的实名认证审核已通过，请退出重新登录，感谢您的支持，祝您使用愉快！";
	//private static final String MESSAGECREDITNOTIY = "尊敬的用户，您的信用卡即需还款，请及时登陆宝数钱包进行还款，如已还款请忽略，祝您使用愉快！";
	//private static final String MESSAGEGAME = "尊敬的用户，您的手机验证码为{0}，本验证码仅用于游戏充值验证，{1}分钟之内有效，请及时查收！";
	@Autowired
	private MessageSendLogService messageSendLogService;

	@RequestMapping("/send")
	@ResponseBody
	public MessageResponse send(MessageRequestModel messageRequestModel,
			Model model, HttpServletRequest request) {		
		MessageResponse messageResponse = new MessageResponse();
		try {
			log.info("短信发送："
					+ ToStringBuilder.reflectionToString(messageRequestModel));
			String returnString=sendMessage(messageRequestModel);
			if (StrUtils.isNotEmpty(returnString)) {
				messageResponse.setReturnCode("9999");
				messageResponse.setErrMsg(returnString);
			} else {				
				messageResponse.setErrMsg("发送成功");
				messageResponse.setReturnCode("0000");
				// 记录短信发送记录
				this.saveMessageSendLog(messageRequestModel, messageRequestModel.getVerifyCode());
			}
			return messageResponse;
		} catch (Exception e) {
			log.error("短信发送异常", e);
			messageResponse.setReturnCode("9999");
			messageResponse.setErrMsg("短信发送异常");
			return messageResponse;
		}
	}

	/**
	 * 发送短信
	 * @throws ClientException 
	 */
	private String sendMessage(MessageRequestModel messageRequestModel) throws ClientException {
		String verifyCode = PmpUtils.getNumberRandomString(6);
		messageRequestModel.setVerifyCode(verifyCode);
		
		String returnString=sendByAliMsg(messageRequestModel);
		return returnString;
		
	}
	
	public String sendByAliMsg(MessageRequestModel model) throws ClientException {
		
		
		
		//阿里云相关的方法以及设置
		
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		
		//替换成你的AK
		final String accessKeyId = "LTAIPMa3nwbfSoVP";//你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = "iwkNT1vEvJnySODopqFulbTpLbqcj0";//你的accessKeySecret，参考本文档步骤2
		
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
		accessKeySecret);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		 //组装请求对象
		 SendSmsRequest request = new SendSmsRequest();
		 //使用post提交
		 request.setMethod(MethodType.POST);
		 //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		 request.setPhoneNumbers(model.getTelephone());
		 //必填:短信签名-可在短信控制台中找到
		 request.setSignName("鹏泰投资");
		 //必填:短信模板-可在短信控制台中找到
		 request.setTemplateCode(getMsgTemp(model));
		 //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		 //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		 request.setTemplateParam("{\"code\":\""+model.getVerifyCode()+"\"}");
		 //可选-上行短信扩展码(无特殊需求用户请忽略此字段)
		 //request.setSmsUpExtendCode("90997");
		 //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		 //request.setOutId("yourOutId");
		 
		//请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			return null;
		}else{
			return sendSmsResponse.getMessage();
		}
	}
	
	
	
	/**
	 * 以前的短信网关
	 * @throws Exception 
	 */
	private String sendByDefault(MessageRequestModel messageRequestModel) throws Exception{
		String msgTmp=getMsgTemp(messageRequestModel);
		if(StrUtils.isEmpty(msgTmp)) {
			return "参数异常，不支持短信类型";
		}
		String uri = PropertyUtil.getValue("messageAddr");// 应用地址
		String account = PropertyUtil.getValue("messageAccount");// 账号
		String pswd = PropertyUtil.getValue("messagePwd");// 密码//
															// 手机号码，多个号码使用","分割
		
		boolean needstatus = true;// 是否需要状态报告，需要true，不需要false
		String product = null;// 产品ID
		String extno = null;// 扩展码

		String returnString = HttpSender.batchSend(uri, account, pswd,
				messageRequestModel.getTelephone(), msgTmp, needstatus,
				product, extno);
		log.info("短信发送：" + returnString);
		int position = returnString.indexOf(",");
		if (null != returnString
				&& "0".equals(returnString.substring(position + 1,
						position + 2))) {
			return null;
		} else {
			return returnString;
		}
	}
	/**
	 * 短信模版
	 */
	private String getMsgTemp(MessageRequestModel messageRequestModel) {
		String content = null;// 短信内容
		String verifyCode=messageRequestModel.getVerifyCode();
		if (MobileCommonHelper.MESSAGETYPE_REGISTER
				.equals(messageRequestModel.getMessageType())) {
			content = MobileCommonHelper.MESSAGETYPE_REGISTER_T;
		} else if (MobileCommonHelper.MESSAGETYPE_FORGETPWD
				.equals(messageRequestModel.getMessageType())) {
			content = MobileCommonHelper.MESSAGETYPE_FORGETPWD_T;
		} else if (MobileCommonHelper.MESSAGETYPE_USERREVIEW
				.equals(messageRequestModel.getMessageType())) {
			content = MobileCommonHelper.MESSAGETYPE_USERREVIEW_T;
		}else if (MobileCommonHelper.MESSAGETYPE_SETTLE_TYPE
				.equals(messageRequestModel.getMessageType())) {
			content = MobileCommonHelper.MESSAGETYPE_SETTLE_TYPE_T;
		}else {
			log.info("不支持短信类型");
		}
		return content;
	}
	/**
	 * 保存短信发送记录
	 * 
	 * @param messageRequestModel
	 * @param verifyCode
	 */
	private void saveMessageSendLog(MessageRequestModel messageRequestModel,
			String verifyCode) {
		MessageSendLogModel temp = new MessageSendLogModel();
		temp.setCreateDate(new Date());
		temp.setExpireDate(DateUtils.addDateByMinute(new Date(),
				MobileCommonHelper.SYSMESSAGETIMEOUT));
		temp.setTelphone(messageRequestModel.getTelephone());
		temp.setMessageType(messageRequestModel.getMessageType());
		temp.setVerifyCode(verifyCode);
		messageSendLogService.add(temp);
	}

}
